local extension = Package:new("fengyukaimu")
extension.extensionName = "hanjin"

local U = require "packages/utility/utility"

Fk:loadTranslationTable { ["fengyukaimu"] = "风雨开幕" }

local hj_liubian = General:new(extension, "hj__liubian", "qun", 3)

local hj_tongge = fk.CreateTriggerSkill {
  name = "hj_tongge",
  anim_type = "defensive",
  events = { fk.TargetConfirmed },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.type ==
      Card.TypeTrick
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(2, self.name)
    player.room:askForDiscard(player, 2, 2, true, "tongge", false)
    local cards
    if player.room:askForSkillInvoke(player.room.current, "tongge", nil,
        "#tongge-drawother") then
      player.room.current:drawCards(2, self.name)
      cards = player.room:askForDiscard(player.room.current, 2, 2, true,self.name,false,".",
        "#tongge-discard")
    end
    if cards == nil then return end
    local ids = table.filter(cards, function(c)
      return (Fk:getCardById(c)).type == Card.TypeEquip
    end)
    if #ids == 0 then return end
    --[[if #cards >=1 and Fk:getCardById(cards[1]).type == Card.TypeEquip then
      ids[#ids+1] = cards[1]
    end
    if #cards >=2 and Fk:getCardById(cards[2]).type == Card.TypeEquip then
      ids[#ids+1] = cards[2]
    end]]
    local r = U.askForUseRealCard(player.room, player, ids, ".", self.name,
      "#tongge-use",
      { expand_pile = ids, bypass_times = true },
      false, true)
  end
}
local hj_xiaju = fk.CreateFilterSkill {
  name = "hj_xiaju",
  frequency = Skill.Compulsory,
  card_filter = function(self, to_select, player)
    return player:hasSkill(self.name) and #player:getCardIds("h") <=
      #player:getCardIds("e") and to_select.suit == Card.Heart and
      not table.every(player:getCardIds("h"),
        function(element, index, array)
          return element ~= to_select.id
        end)
  end,
  view_as = function(self, to_select)
    return Fk:cloneCard("ex_nihilo", to_select.suit, to_select.number)
  end
}
local hj_xiaju_swap = fk.CreateTriggerSkill {
  name = "#hj_xiaju_swap",
  frequency = Skill.Compulsory,
  mute = true,
  events = { fk.TurnStart, fk.EventPhaseChanging, fk.TurnEnd },
  can_trigger = function(self, event, target, player, data)
    if target ~= player or (not player:hasSkill(self.name, true)) then
      return false
    end
    if event == fk.TurnStart and #player:getCardIds("e") ~= 0 and
      #player:getCardIds("e") ~= 5 then
      return true;
    end
    if event == fk.TurnEnd then return true end
    local l_stage = player:getMark("xiaju_stage")
    if event == fk.EventPhaseChanging and l_stage ~= 0 then
      return l_stage == data.to or data.to == Player.Discard
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.TurnEnd then
      player.room:setPlayerMark(player, "xiaju_stage", 0)
      return
    end
    if event == fk.TurnStart then
      player.room:setPlayerMark(player, "xiaju_stage", #player:getCardIds(
        "e") + Player.Start - 1)
      player.room:sendLog {
        type = "#PhaseChanged",
        from = player.id,
        arg = Util.PhaseStrMapper(
          #player:getCardIds("e") + Player.Start - 1),
        arg2 = "phase_discard"
      }
      player.room:sendLog {
        type = "#PhaseChanged",
        from = player.id,
        arg2 = Util.PhaseStrMapper(
          #player:getCardIds("e") + Player.Start - 1),
        arg = "phase_discard"
      }
    else
      local l_stage = player:getMark("xiaju_stage")
      if l_stage == data.to then
        data.to = Player.Discard
      else
        data.to = l_stage
      end
    end
  end
}
local hj_zhemian = fk.CreateTriggerSkill {
  name = "hj_zhemian$",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return (player ~= target and player:hasSkill(self) and target.phase ==
      Player.Start and
      table.every(player.room:getOtherPlayers(target), function(p)
        return p:getHandcardNum() <= target:getHandcardNum()
      end) and target.kingdom == "qun")
  end,
  on_cost = function(self, event, target, player, data)
    local targets = {}
    for _, value in ipairs(player.room:getOtherPlayers(player)) do
      if value:canMoveCardsInBoardTo(player, 'e') or
        player:canMoveCardsInBoardTo(value, 'e') then
        table.insert(targets, value.id)
      end
    end
    if (#targets > 0) then
      local result = player.room:askForChoosePlayers(target, targets, 1,
        1, "zhemian-choose",
        self.name,
        true)
      if result == nil or #result == 0 then return; end
      self.cost_data = { tos = result }
      return true
    else
      return;
    end
  end,

  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = room:getPlayerById(self.cost_data.tos[1])
    local result = room:askForMoveCardInBoard(target, targets, player,
      self.name, "e")
  end
}
hj_xiaju:addRelatedSkill(hj_xiaju_swap)
hj_liubian:addSkill(hj_tongge)
hj_liubian:addSkill(hj_xiaju)

hj_liubian:addSkill(hj_zhemian)

Fk:loadTranslationTable {
  ["hj__liubian"] = "刘辩",
  ["#hj__liubian"] = "龍影沖闇",
  ["designer:hj__liubian"] = "静谦",
  ["cv:hj__liubian"] = "无",
  ["illustrator:hj__liubian"] = "DH",
  ["hj_tongge"] = "恸歌",
  [":hj_tongge"] = "当你成为锦囊牌的目标后，你可以摸两张牌然后弃两张牌，则当前回合角色也可这么做，然后你可以使用其以此法弃置的一张装备牌.",
  ["#tongge-draw"] = "摸两张牌并弃两张牌然后当前回合角色也可这么做",
  ["#tongge-drawother"] = "摸两张牌并弃两张牌然后刘辩可以用弃牌中一张装备牌",
  ["#tongge-use"] = "你可以使用其中的装备牌",
  ["#tongge-discard"] = "弃两张牌然后刘辩可以使用其中一张一张装备牌",
  ["hj_xiaju"] = "挟局",
  ["#hj_xiaju_swap"] = "挟局",
  [":hj_xiaju"] = "锁定技，若你的手牌数不大于X，你的♥️手牌视为【无中生有】；你的回合开始时交换本回合第X个阶段和弃牌阶段（X为你装备区内的牌数）。",
  ["hj_zhemian"] = "折冕",
  [":hj_zhemian"] = "主公技，群势力角色的准备阶段，若其手牌全场最多，其可以选择一名角色，然后其可以将该角色装备区一张牌移至你的装备区，或你的装备区一张牌移至该装备区。",
  ["zhemian-choose"] = "折冕：选择一名角色，然后你可以选择将其装备区一张牌移至你的装备区，或你装备区一张牌移至其装备区"
}

local hj_caohuan = General:new(extension, "hj__caohuan", "wei", 3)

local hj_jinchi = fk.CreateProhibitSkill {
  anim_type = "negative",
  name = "hj_jinchi",
  frequency = Skill.Compulsory,
  is_prohibited = function(self, from, to, card)
    return from:hasSkill(self) and (not to:hasSkill(self)) and
      card:getMark("@@fubing_card") == 0
  end
}

local hj_jinchi_damage = fk.CreateTriggerSkill {
  anim_type = "offensive",
  name = "#hj_jinchi_damage",
  mute = true,
  frequency = Skill.Compulsory,
  events = { fk.DamageCaused, fk.DamageInflicted },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    player.room:addPlayerMark(player, "@fubing_times-turn", 1)
  end
}

local hj_fubing_giveCard = fk.CreateTriggerSkill {
  name = "#hj_fubing_trigger2",
  anim_type = "control",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return player.phase == Player.Start and player:hasSkill(self) and
      #player.room:getOtherPlayers(player) > 0 and
      player:hasSkill(self.name, false)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, value in ipairs(room:getOtherPlayers(player)) do
      local cards = room:askForCard(value, 1, 1, true, self.name, true,
        nil, "#fubing_give-prompt")
      if #cards ~= 0 then
        room:obtainCard(player, cards, false, fk.ReasonGive, value.id,
          self.name)
        room:setPlayerMark(value, "View_as_wei-turn", 1)
      end
    end
  end
}
Fk:loadTranslationTable{
  ["@@ViewAsWei"] = "视为魏势力"
}
local hj_fubing = fk.CreateActiveSkill {
  name = "hj_fubing",
  anim_type = "control",
  target_num = 1,
  card_num = 0,
  prompt = "#hj_fubing-ask",
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards, card,
               extra_data)
    if #selected > 0 then
      return false
    end
    local room = Fk:currentRoom()
    return (room:getPlayerById(to_select).kingdom == "wei" or
        (room:getPlayerById(to_select):getMark("View_as_wei-turn") ~= 0)) and
      (room:getPlayerById(to_select):getMark("@@yifubing-turn") ==
        0 or Self:getMark("@fubing_times-turn") > 0)
  end,
  target_tip = function (self, to_select, selected, selected_cards, card, selectable, extra_data)
    if Fk:currentRoom():getPlayerById(to_select):getMark("View_as_wei-turn") ~= 0 then
      return { {content = "@@ViewAsWei", type = "normal"} }
    end
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1]);
    local player = room:getPlayerById(effect.from)
    local cards = player:getCardIds("h")
    for _, value in ipairs(cards) do
      room:addCardMark(Fk:getCardById(value), "@@fubing_card")
    end
    local r
    if target ~= player then
      r = U.askForUseRealCard(room, target, cards, ".", self.name,
        "#fubing-use",
        { expand_pile = cards, bypass_times = true },
        false, true)
    else
      r = U.askForUseRealCard(room, target, cards, ".", self.name,
        "#fubing-use", nil, false, true)
    end
    if (player:getMark("@@yifubing-turn") ~= 1) then
      room:setPlayerMark(target, "@@yifubing-turn", 1);
    else
      room:removePlayerMark(player, "@fubing_times-turn", 1)
    end

    for _, value in ipairs(cards) do
      room:removeCardMark(Fk:getCardById(value), "@@fubing_card")
    end
  end
}

local hj_yiming = fk.CreateTriggerSkill {
  name = "hj_yiming$",
  events = { fk.DamageCaused, fk.DamageInflicted },
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and
      (target.kingdom == "wei" or target:getMark("@View_as_wei") >
        0)
  end,
  on_use = function(self, event, target, player, data)
    player.room:addPlayerMark(player, "@fubing_times-turn", 1)
  end
}

Fk:loadTranslationTable {
  ["hj__caohuan"] = "曹奂",
  ["#hj__caohuan"] = "魏元帝",
  ["designer:hj__caohuan"] = "庾兰成",
  ["illustrator:hj__caohuan"] = "佚名",
  ["hj_jinchi"] = "浸掣",
  ["#hj_jinchi_damage"] = "浸掣",
  [":hj_jinchi"] = "锁定技，你非因“浮柄”使用的牌无法指定其他角色为目标。当你造成或受到伤害时，“浮柄”可发动次数+1直到本回合结束。",
  ["hj_fubing"] = "浮柄",
  [":hj_fubing"] = "准备阶段开始时，每名其他角色可以交给你一张牌，则其本回合对你视为魏势力。出牌阶段名魏势力角色限一次,你选择一名魏势力角色然后令其观看你的手牌，然后其可使用其中一张（不受次数限制）。",
  ["#hj_fubing_trigger1"] = "浮柄",
  ["#hj_fubing_trigger2"] = "浮柄",
  ["#hj_fubing-ask"] = "浮柄：选择一名魏势力角色，令其使用你的一张手牌",
  ["#fubing-use"] = "你你可以使用曹奂的一张牌",
  ["@@fubing_card"] = "浮柄",
  ["@@yifubing-turn"] = "已发动浮柄",
  ["@fubing_times-turn"] = "浮柄额外次数",
  ["#fubing_give-prompt"] = "你可以交给曹奂一张牌，则本回合你对其视为魏势力角色",
  ["hj_yiming"] = "移命",
  [":hj_yiming"] = "主公技，锁定技，魏势力角色造成或受到伤害时，你用此伤害发动“浸掣”。"
}
hj_fubing:addRelatedSkill(hj_fubing_giveCard)
hj_caohuan:addSkill(hj_fubing)
hj_jinchi:addRelatedSkill(hj_jinchi_damage)
hj_caohuan:addSkill(hj_jinchi)
hj_caohuan:addSkill(hj_yiming)

local hj_lijue = General:new(extension, "hj__lijue", "qun", 4)

local hj_xilve = fk.CreateViewAsSkill {
  name = "hj_xilve",
  anim_type = "switch",
  switch_skill_name = "hj_xilve",
  prompt = function()
    if Self:getSwitchSkillState("hj_xilve") == fk.SwitchYang then
      return "将一张牌当【出其不意】使用"
    end
    return "将一张牌当【趁火打劫】使用"
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == "slash"
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return nil end
    local name = (Self:getSwitchSkillState("hj_xilve") == fk.SwitchYang and
      "unexpectation" or "looting")
    if not Fk.all_card_types[name] then return nil end
    local c = Fk:cloneCard(name)
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
  enabled_at_play = function(self, player)
    return not player:isKongcheng() and table.find(player:getCardIds("h"),
      function(id)
        return Fk:getCardById(id).trueName == "slash"
      end)
  end,
  after_use = function(self, player, use) end
}
local hj_xilve_delay = fk.CreateTriggerSkill {
  name = "#hj_xilve_delay",
  mute = true,
  events = { fk.CardUseFinished },
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil,
      "#xilve_delay-choose")
  end,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self.name) and target == player and data.card and
      table.contains(data.card.skillNames, "hj_xilve") and
      not data.damageDealt
  end,
  on_use = function(self, event, target, player, data)
    local all_slots = {
      "WeaponSlot", "ArmorSlot", "DefensiveRideSlot", "OffensiveRideSlot",
      "TreasureSlot"
    }
    local choices = {}
    for _, equip_slot in ipairs(all_slots) do
      if table.contains(player.sealedSlots, equip_slot) then
        table.insert(choices, equip_slot)
      end
    end
    if #choices > 0 then
      local choice = player.room:askForChoice(player, choices, self.name,
        "#xilve-choice", false)
      player.room:resumePlayerArea(player, { choice })
      player:endPlayPhase()
    end
  end
}

local hj_huigang = fk.CreateTriggerSkill {
  anim_type = "drawcard",
  name = "hj_huigang",
  frequency = Skill.Compulsory,
  on_cost = Util.TrueFunc,
  events = { fk.DamageCaused },
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and target == player) then
      return false
    end
    local all_slots = {
      "WeaponSlot", "ArmorSlot", "DefensiveRideSlot", "OffensiveRideSlot",
      "TreasureSlot"
    }
    local choices = {}
    for _, equip_slot in ipairs(all_slots) do
      if not table.contains(player.sealedSlots, equip_slot) then
        table.insert(choices, equip_slot)
      end
    end
    return #choices > 0
  end,
  on_use = function(self, event, target, player, data)
    local all_slots = {
      "WeaponSlot", "ArmorSlot", "DefensiveRideSlot", "OffensiveRideSlot",
      "TreasureSlot"
    }
    local choices = {}
    for _, equip_slot in ipairs(all_slots) do
      if not table.contains(player.sealedSlots, equip_slot) then
        table.insert(choices, equip_slot)
      end
    end
    local recover = false
    if #choices > 0 then
      local choice = player.room:askForChoice(player, choices, self.name,
        "#xilve-choice", false)
      recover = #player:getCardIds(choice) == 0
      player.room:abortPlayerArea(player, { choice })
      local n = player:getHandcardNum() - (5 - #player.sealedSlots)
      if n < 0 then
        player:drawCards(-n, self.name)
      elseif n > 0 then
        player.room:askForDiscard(player, n, n, false, self.name, false)
      end
    end
    if recover then
      player.room:recover({
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name
      })
    end
  end
}

hj_xilve:addRelatedSkill(hj_xilve_delay)
hj_lijue:addSkill(hj_xilve)
hj_lijue:addSkill(hj_huigang)

Fk:loadTranslationTable {
  ["hj__lijue"] = "李傕",
  ["#hj__lijue"] = "挟君掠民",
  ["designer:hj__lijue"] = "静谦",
  ["illustrator:hj__lijue"] = "MUMU",
  ["hj_xilve"] = "袭掠",
  ["#hj_xilve_delay"] = "袭掠",
  ["#xilve_delay-choose"] = "是否恢复一个装备栏然后结束出牌阶段",
  [":hj_xilve"] = "转换技，出牌阶段，阳：你可以将【杀】当【出其不意】使用。阴：你可以将【杀】当【趁火打劫】使用。你以此法使用锦囊牌后，若此牌未造成伤害，你可恢复一个装备栏并结束出牌阶段。",
  ["hj_huigang"] = "隳纲",
  [":hj_huigang"] = "锁定技，当你造成伤害后，你废除一个装备栏，然后将手牌调整至X张（X为剩余装备栏数），若你废除的是有装备的装备栏，你回复1点体力。"
}

local hj_sunhao = General:new(extension, "hj__sunhao", "wu", 6)

Fk:loadTranslationTable {
  ["hj__sunhao"] = "孙皓",
  ["#hj__sunhao"] = "暴戾恣睢",
  ["designer:hj__sunhao"] = "庾兰成",
  ["illustrator:hj__sunhao"] = "匠人绘",
  ["hj_zhoushi"] = "骤蚀",
  [":hj_zhoushi"] = "出牌阶段每项限一次，你可以执行其中一项：①重铸一张牌；②失去1点体力；③减1点体力上限然后令其中一个选项可选次数+1。；选择后你令一名其他角色摸一张牌，然后弃置X张牌（X为此技能本回合发动次数）",
  ["hj_zhoushi-choose"] = "选择一项，然后你令一名其他角色摸一张牌，然后弃置%arg张牌",
  ["#hj_zhoushi-add"] = "令以下项本回合能额外发动一次",
  ["hj_zhoushi-recast"] = "重铸",
  [":hj_zhoushi-recast"] = "重铸一张牌。",
  ["#hj_zhoushi-recastCard"] = "骤蚀：重铸一张牌",
  ["hj_zhoushi-loseHp"] = "扣血",
  [":hj_zhoushi-loseHp"] = "失去1点体力。",
  ["hj_zhoushi-loseMaxHp"] = "扣上限",
  [":hj_zhoushi-loseMaxHp"] = "减1点体力上限然后令其中一个选项可选次数+1。",
  ["hj_canjue"] = "残决",
  [":hj_canjue"] = "锁定技，一名角色失去最后一张牌后，你摸一张牌。 ",
  ["hj_qingwu"] = "倾吴",
  [":hj_qingwu"] = "主公技，其他吴势力角色的准备阶段开始时，你可以对其发动由其选项且X为选项序号的“骤蚀”。"
}

local hj_zhoushi = fk.CreateActiveSkill{
  name = "hj_zhoushi",
  card_num = 0,
  target_num = 1;
  card_filter = Util.FalseFunc,
  anim_type = "control",
  target_filter = function (self, to_select, selected, selected_cards, card, extra_data)
    return to_select ~= Self.id and #selected == 0
  end,
  can_use = function (self, player, card, extra_data)
    local marks = player:getTableMark("#hj_zhoushi")
    return not table.every(marks,function (element, index, array)
      return element == 0
    end)
  end,
  on_use = function (self, room, effect)
    local player = room:getPlayerById(effect.from)
    local mark_table = player:getTableMark("#hj_zhoushi")
    local choices = {}
    if mark_table[1] > 0 then
      table.insert(choices,"hj_zhoushi-recast")
    end
    if mark_table[2] >0 then
      table.insert(choices,"hj_zhoushi-loseHp")
    end
    if mark_table[3] >0 then
      table.insert(choices,"hj_zhoushi-loseMaxHp")
    end
    local choice = room:askForChoice(player,choices,self.name,"hj_zhoushi-choose:::"..tostring(player:usedSkillTimes(self.name)),true,{"hj_zhoushi-recast","hj_zhoushi-loseHp","hj_zhoushi-loseMaxHp"})
    if choice == "hj_zhoushi-recast" then
      local recast_card = room:askForCard(player,1,1,true,self.name,false,".","#hj_zhoushi-recastCard")
      if #recast_card == 0 then return false end
      room:recastCard(recast_card,player,self.name)
      mark_table[1] = mark_table[1]-1
    elseif choice == "hj_zhoushi-loseHp" then
      room:loseHp(player,1,self.name)
      mark_table[2] = mark_table[2]-1
    else
      room:changeMaxHp(player,-1)
      local choice = room:askForChoice(player,{"hj_zhoushi-recast","hj_zhoushi-loseHp","hj_zhoushi-loseMaxHp"},self.name,"#hj_zhoushi-add",true)
      mark_table[3] = mark_table[3]-1
      if choice == "hj_zhoushi-recast" then
        mark_table[1] = mark_table[1]+1
      elseif choice == "hj_zhoushi-loseHp" then
        mark_table[2] = mark_table[2]+1
      else
        mark_table[3] = mark_table[3]+1
      end
    end
    room:setPlayerMark(player,"#hj_zhoushi",mark_table)
    local target = room:getPlayerById(effect.tos[1])
    room:drawCards(target,1,self.name)
    room:askForDiscard(target,player:usedSkillTimes(self.name),player:usedSkillTimes(self.name),true,self.name,false)
  end,
}

local hj_zhoushi_mark = fk.CreateTriggerSkill{
  name = "#hj_zhoushi_mark",
  main_skill = hj_zhoushi,
  refresh_events = {fk.TurnStart},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_refresh = function (self, event, target, player, data)
    local mark = {1,1,1}
    player.room:setPlayerMark(player,"#hj_zhoushi",mark)
  end
}

local hj_canjue = fk.CreateTriggerSkill{
  name = "hj_canjue",
  anim_type = "drawcard",
  events = {fk.AfterCardsMove},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    for _, move in ipairs(data) do
      for _, info in ipairs(move.moveInfo) do
        if info.fromArea == Card.PlayerHand then
          if move.from ~= nil and player.room:getPlayerById(move.from):isKongcheng()then 
            return true
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}

local hj_qingwu = fk.CreateTriggerSkill{
  name = "hj_qingwu$",
  events = {fk.EventPhaseStart},
  anim_type = "control",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target~=player and target.phase == Player.Start and target.kingdom == "wu"
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player,self.name,nil)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(target,{"hj_zhoushi-recast","hj_zhoushi-loseHp","hj_zhoushi-loseMaxHp"},self.name,"hj_qingwu-choose",true)
    room:drawCards(target,1,self.name)
    if choice == "hj_zhoushi-recast" then 
      local recast_card = room:askForCard(player,1,1,true,self.name,false,".","#hj_zhoushi-recastCard")
      if #recast_card == 0 then return false end
      room:recastCard(recast_card,player,self.name)
      room:askForDiscard(target,1,1)
    elseif choice == "hj_zhoushi-loseHp" then
      room:loseHp(player,1,self.name)
      room:askForDiscard(target,2,2)
    else
      room:changeMaxHp(player,-1)
      room:askForDiscard(target,3,3)
    end
  end
}

hj_zhoushi:addRelatedSkill(hj_zhoushi_mark)
hj_sunhao:addSkill(hj_zhoushi)
hj_sunhao:addSkill(hj_canjue)
hj_sunhao:addSkill(hj_qingwu)



local hj_simayan = General:new(extension, "hj__simayan","jin", 3)

Fk:loadTranslationTable {
  ["hj__simayan"] = "司马炎",
  ["#hj__simayan"] = "安世的真龙",
  ["designer:hj__simayan"] = "司馬師",
  ["hj_ruimang"]= "锐芒",
  [":hj_ruimang"] = "锁定技，你的非锁定技能失效。你手牌数未变化过的阶段结束时，你视为使用一张无距离限制的【杀】，若此牌未造成伤害，你将手牌摸至体力上限，然后此技能失效直到回合结束。",
  ["@@hj_ruimang-invalid"] = "锐芒失效",
  ["hj_weizhi"] = "危卮",
  [":hj_weizhi"] = "出牌阶段限一次，你可以令两名其他角色拼点，赢的角色摸一张牌并对没赢的角色造成一点火焰伤害，然后本回合未以此法参与过拼点的角色可以与赢的角色重复此流程。",
  ["hj_liepo"] = "迾破",
  ["@@hj_liepo-turn"] = "迾破",
  [":hj_liepo"] = "出牌阶段结束时，你可以令所有本回合所有拼点没赢的角色各弃置一张手牌，没牌则改为令其横置。",
  ["hj_juekuang"] = "决况",
  [":hj_juekuang"] = "主公技，锁定技，你的阶段开始时，其他晋势力武将可以交给你一张伤害牌并调整“锐铓”的失效状态。"
}

local hj_ruimang = fk.CreateTriggerSkill{
  name = "hj_ruimang",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseEnd},
  anim_type = "offensive",
  can_trigger = function (self, event, target, player, data)
    if target == player and player:hasSkill(self) and player.phase > 1 and player.phase < 8 then
      return #player.room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
        for _, move in ipairs(e.data) do
          if move.to == player.id and move.toArea == Card.PlayerHand then
            return true
          end
          if move.from == player.id then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerHand then
                return true
              end
            end
          end
        end return false
      end, Player.HistoryPhase) == 0
    end
  end,
  on_trigger = function (self, event, target, player, data)
    local dat = U.askForUseVirtualCard(player.room,player,"slash",nil,self.name,nil,false,true,true,true);
    if dat ~= nil and not dat.damageDealt then
      local card_num = player.maxHp - player:getHandcardNum()
      if card_num>0 then
        player.room:drawCards(player,card_num,self.name)
      end
      player.room:invalidateSkill(player,self.name)
      player.room:addPlayerMark(player,"@@hj_ruimang-invalid")
    end
  end,
  refresh_events = {fk.AfterTurnEnd},
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(self,true,true)
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:validateSkill(player,self.name)
    player.room:setPlayerMark(player,"@@hj_ruimang-invalid",0)
  end
}
local hj_ruimang_invalid = fk.CreateInvaliditySkill {
  name = "#hj_ruimang_invalid",
  invalidity_func = function(self, from, skill)
    return from:hasSkill(self, true, true) and skill:isPlayerSkill(from) and skill.frequency ~= Skill.Compulsory and from:hasSkill(hj_ruimang,false)  
  end
}

local hj_weizhi = fk.CreateActiveSkill{
  name = "hj_weizhi",
  anim_type = "offensive",
  target_num = 2,
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_filter = function (self, to_select, selected, selected_cards, card, extra_data)
    return to_select ~= Self.id and #selected < 2
  end,
  can_use = function (self, player, card, extra_data)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function (self, room, effect)
    local target1,target2 = room:getPlayerById(effect.tos[1]),room:getPlayerById(effect.tos[2])
    local result
    local players = room:getAlivePlayers()
    table.removeOne(players,target1)
    table.removeOne(players,target2)
    while true do
      result = target1:pindian({target2},self.name)
      if result.results[target2.id].winner then
        if result.results[target2.id].winner == target1 then
          room:damage{
            from = target1,
            to = target2,
            damageType = fk.FireDamage,
            damage = 1
          }
          if #players >0 then
            local mark = false
            for index, value in ipairs(players) do
              if value:isAlive() and   value:canPindian(target1,false,false) and (room:askForSkillInvoke(value,self.name,nil,"#hj_weizhi-askPindian")) then
                mark = true
                target2 = value
                break
              end
            end
            if mark == false then
              return
            end
          else
            return
          end
        else
          room:damage{
            from = target2,
            to = target1,
            damageType = fk.FireDamage,
            damage = 1
          }
          if #players >0 then
            local mark = false
            for index, value in ipairs(players) do
              if value:isAlive() and value:canPindian(target2,false,false) and (room:askForSkillInvoke(value,self.name,nil,"#hj_weizhi-askPindian")) then
                mark = true
                target1 = value
                break
              end
            end
            if mark == false then
              return
            end
          else
            return
          end
        end
      else
        return;
      end
      table.removeOne(players,target1)
      table.removeOne(players,target2)
    end
  end
}

local hj_liepo = fk.CreateTriggerSkill{
  name = "hj_liepo",
  events = {fk.EventPhaseEnd},
  anim_type = "control",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and player.phase == Player.Play
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player,self.name) 
  end,
  on_use = function (self, event, target, player, data)
    local tos = table.filter(player.room:getAlivePlayers(),function (element, index, array)
      return element:getMark("@@hj_liepo-turn")>0
    end)
    for index, value in ipairs(tos) do
      if value:getHandcardNum()>0 then
        player.room:askForDiscard(value,1,1,false,self.name,false,".","#hj_liepo-discard")
      else
        value:setChainState(true)
      end
    end
  end,
  refresh_events = {
    fk.PindianResultConfirmed
  },
  can_refresh = Util.TrueFunc;
  on_refresh = function (self, event, target, player, data)
    if data.winner then
      if data.winner == data.from then
        player.room:addPlayerMark(data.to,"@@hj_liepo-turn")
      else
        player.room:addPlayerMark(data.from,"@@hj_liepo-turn")
      end
    else
      player.room:addPlayerMark(data.to,"@@hj_liepo-turn")
      player.room:addPlayerMark(data.from,"@@hj_liepo-turn")
    end
  end
}

local hj_juekuang = fk.CreateTriggerSkill{
  name = "hj_juekuang$",
  frequency = Skill.Compulsory,
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase > 1 and player.phase < 8
  end,
  on_trigger = function (self, event, target, player, data)
    local players = table.filter(player.room:getOtherPlayers(player),function (element, index, array)
      return element.kingdom == "jin"
    end)
    for index, value in ipairs(players) do
      local table = player.room:askForYiji(value,nil,{player},self.name,0,1,"#hj_juekuang-chooseCard")
      if #table>0 then
        if player:hasSkill(hj_ruimang,true) and player:getMark("@@hj_ruimang-invalid") > 0  then
          player.room:validateSkill(player,hj_ruimang.name)
          player.room:setPlayerMark(player,"@@hj_ruimang-invalid",0)
        elseif player:hasSkill(hj_ruimang,true) and player:getMark("@@hj_ruimang-invalid") == 0 then
          player.room:invalidateSkill(player,hj_ruimang.name)
          player.room:addPlayerMark(player,"@@hj_ruimang-invalid")
        end
      end
    end
  end
}

hj_ruimang:addRelatedSkill(hj_ruimang_invalid)
hj_simayan:addSkill(hj_ruimang)
hj_simayan:addSkill(hj_weizhi)
hj_simayan:addSkill(hj_liepo)
hj_simayan:addSkill(hj_juekuang)

--[[local dongjue = General:new(extension, "hj__dongjue","shu", 3)

local gongtuo = fk.CreateActiveSkill{
  name = "gongtuo",
  switch_skill_name = "gongtuo",
  anim_type = "switch",
  can_use = function (self, player, card, extra_data)
    return player:hasSkill(self)
  end,
  card_num = function (self)
    if Self:getSwitchSkillState(self.name) == fk.SwitchYang then
      return 0
    else
      return Self:usedSkillTimes(self.name) + 1
    end
  end,
  card_filter = function (self, to_select, selected, selected_targets)
    if Self:getSwitchSkillState(self.name) == fk.SwitchYang then
      return false
    else
      return true
    end
  end,
  prompt = function (self, selected_cards, selected_targets)
    if Self:getSwitchSkillState(self.name) == fk.SwitchYang then
      return "摸"..(Self:usedSkillTimes(self.name) + 1).."张牌"
    else
      return "弃置"..(Self:usedSkillTimes(self.name) + 1).."张牌"
    end
  end,
  on_use = function (self, room, effect)
    local player = room:getPlayerById(effect.from)
    local n = player:usedSkillTimes(self.name)
    if player:getSwitchSkillState(self.name,true) == fk.SwitchYang then
      room:drawCards(player,n)
    else
      room:throwCard(effect.cards,self.name,player,player)
    end
    local eqhp_players = {}
    for index, value in ipairs(room:getAlivePlayers()) do
      if value.hp == n then
        table.insert(eqhp_players,value.id)
      end
    end
    if #eqhp_players == 0 then
      return
    end
    local choice = room:askForChoosePlayers(player,eqhp_players,1,1,"躬妥：请选择一名体力值为"..n.."的玩家令其摸一张牌或弃一张牌",self.name,true)
    if #choice > 0 then
      local choice_list = {"令其摸牌","令其弃牌"}
      local result = room:askForChoice(player,choice_list,self.name,"选择摸牌还是弃牌")
      if result == "令其摸牌" then
        room:drawCards(room:getPlayerById(choice[1]),1,self.name)
      else
        room:askForDiscard(room:getPlayerById(choice[1]),1,1,true,self.name,false)
      end
    end
  end
}

dongjue:addSkill(gongtuo)

Fk:loadTranslationTable{
  ["hj__dongjue"] = "董厥",
  ["#hj__dongjue"] = "良慎失匡",
  ["designer:hj__dongjue"] = "静谦",
  ["gongtuo"] = "躬妥",
  [":gongtuo"] = "转换技，出牌阶段，阳：你可以摸X张牌,然后让一名体力值为X的角色摸一张牌或弃一张牌。阴：你可以弃X张牌,然后让一名体力值为X的角色摸一张牌或弃一张牌（X为本回合发动此技能次数）。",
  ["liai"] = "离哀",
  [":liai"] = "锁定技，当你的手牌数变化后，若与体力值相等：你令体力值唯一最小的角色回复1点体力；若为0：你令体力值唯一最大的角色失去1点体力。"
}
]]

local zhangjiao  = General(extension,"hj__zhangjiao","qun",3)

local dunan = fk.CreateTriggerSkill{
  name = "hj__dunan",
  anim_type = "control",
  events = {fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and #player.room.logic:getActualDamageEvents(1,Util.TrueFunc,Player.HistoryTurn) > 0
  end,
  derived_piles = "$hj__zhangjiao_dao",
  frequency = Skill.Compulsory,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player:drawCards(1, self.name)
    if not (player.dead or player:isKongcheng()) then
      local card = room:askForCard(player, 1, 1, true, self.name, false, nil, "#hj__zhangjiao_dunan_push")
      player:addToPile("$hj__zhangjiao_dao", card, true, self.name)
    end
  end
}

local shoushu = fk.CreateTriggerSkill{
  name = "hj__shoushu",
  anim_type = "drawcard",
  events = {fk.TurnStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target == player and #player:getPile("$hj__zhangjiao_dao") > 0
  end,
  on_cost = function (self, event, target, player, data)
    local types = {}
    for _, id in ipairs(player:getPile("$hj__zhangjiao_dao")) do
      table.insertIfNeed(types, Fk:getCardById(id).type)
    end
    local all_choices = {"#hj__zhangjiao_aquireSkill","#hj__zhangjiao_recast:::"..#types,"#hj__equipPeace:::"..#types}
    local choices = {all_choices[1]}
    local targets = table.filter(player.room:getAlivePlayers(),function (element, index, array)
      return #player:getCardIds("he") >= #types 
    end)
    if #targets > 0 then
      table.insert(choices,all_choices[2])
    end
    table.insert(choices,all_choices[3])
    local result = player.room:askForChoices(player,choices,#types,#types,self.name,"#hj__shoushu_choices:::"..#types,true,false,all_choices)
    if result == 0 then
      return
    end
    self.cost_data = self.cost_data or {}
    self.cost_data.all_choices = all_choices
    self.cost_data.choices = result
    self.cost_data.types = types
    return true
  end,
  on_use = function (self, event, target, player, data)
    local choices = self.cost_data.all_choices
    local result = self.cost_data.choices
    local types = self.cost_data.types
    local room = player.room
    if table.contains(result,choices[1]) then
      room:handleAddLoseSkills(player,"hj__jiumin",self.name)
      if player.dead then
        return
      end
    end
    if table.contains(result,choices[2]) then
      local target = room:askForChoosePlayers(player,table.map(table.filter(player.room:getAlivePlayers(),function (element, index, array)
        return #element:getCardIds("he")>=#types
      end),Util.IdMapper),1,1,"#hj__shoushu_choose2recast:::"..#types,self.name,true)
      local cards = room:askForCard(room:getPlayerById(target[1]),#types,#types,true,self.name,false,".")
      room:recastCard(cards,player,self.name)
      if player.dead then
        return
      end
    end
    if table.contains(result,choices[3]) then
      local targets = player.room:askForChoosePlayers(player,table.map(player.room:getAlivePlayers(),Util.IdMapper),1,#types,"#hj__shoushu_choose2draw:::"..#types,self.name,false)
      room:sortPlayersByAction(targets)
      for _, p in ipairs(targets) do
        local target = room:getPlayerById(p)
        if target.dead then
          goto continue
        end
        room:drawCards(target,1,self.name)
        if player.dead then
          return
        end
          ::continue::
      end
      local spell = U.prepareDeriveCards(room, {{"js__peace_spell", Card.Heart, 3}}, "shoushu_spell")[1]
      if table.contains({Card.Void, Card.DrawPile, Card.DiscardPile , Card.PlayerEquip ,Card.PlayerJudge}, player.room:getCardArea(spell)) then
        room:moveCardIntoEquip(player, spell, self.name, true, player)
      end
    end
  end,
  refresh_events = {fk.AfterRoundEnd},
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill("hj__jiumin")
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:handleAddLoseSkills(player,"-hj__jiumin",self)
  end
}

local jiumin = fk.CreateActiveSkill{
  name = "hj__jiumin",
  anim_type = "support",
  expand_pile = "$hj__zhangjiao_dao",
  prompt = "#hj__jiumin_prompt",
  can_use = function (self, player, card, extra_data)
    return player:usedSkillTimes(self.name) < 1 and #player:getPile("$hj__zhangjiao_dao")>0
  end,
  feasible = function (self, selected, selected_cards, player)
    return #selected == #selected_cards
  end,
  card_filter = function (self, to_select, selected, player)
    return table.contains(player:getPile("$hj__zhangjiao_dao"),to_select)
  end,
  target_filter = function (self, to_select, selected, selected_cards, card, extra_data, player)
    return to_select ~= player.id
  end,
  on_use = function (self, room, effect)
    room:throwCard(effect.cards,self.name,room:getPlayerById(effect.from))
    table.forEach(effect.tos,function (element, index, array)
      local target = room:getPlayerById(element)
      room:handleAddLoseSkills(target,"jibing",self.name)
    end)
  end
}

local jiumin_delay = fk.CreateTriggerSkill{
  name = "#jiumin_delay",
  mute = true,
  events = {fk.RoundEnd},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self)
  end,
  frequency = Skill.Compulsory,
  on_use = function (self, event, target, player, data)
    player:broadcastSkillInvoke("hj__jiumin")
    player.room:notifySkillInvoked(player,"hj__jiumin","drawcard")
    table.forEach(player.room:getOtherPlayers(player),function (element, index, array)
      local cards = element:getPile("$mayuanyi_bing")
      player.room:obtainCard(player,cards,true,fk.ReasonPrey,player.id,"hj__jiumin")
    end)
  end
}

jiumin:addRelatedSkill(jiumin_delay)
Fk:addSkill(jiumin)

local huangjin = fk.CreateTriggerSkill{
  name = "hj__huangjin$",
  anim_type = "drawcard",
  events = {fk.AfterSkillEffect},
  can_trigger = function (self, event, target, player, data)
    return data.name == "jibing" and target~= player and player:hasSkill(self)
  end,
  on_use = function (self, event, target, player, data)
    player.room:drawCards(player,1,self.name)
  end
}

zhangjiao:addSkill(dunan)
zhangjiao:addSkill(shoushu)

zhangjiao:addRelatedSkill(jiumin)
zhangjiao:addRelatedSkill("jibing")

zhangjiao:addSkill(huangjin)

Fk:loadTranslationTable{
  ["hj__zhangjiao"] = "张角",
  ["designer:hj__zhangjiao"] = "晓诺",
  ["#hj__zhangjiao"] = "践道救民",

  ["hj__dunan"] = "睹难",
  [":hj__dunan"] = "锁定技，有角色受到伤害的回合结束时，你摸一张牌并将一张牌置于武将牌上成为“道”。",
  ["$hj__zhangjiao_dao"] = "道",
  ["#hj__zhangjiao_dunan_push"] = "睹难：将一张牌置于武将牌上（称为“道”）",
  ["hj__shoushu"] = "授书",
  [":hj__shoushu"] = "准备阶段，你可以选择X项：1.获得“救民”直到本轮结束。2.可以令一名角色重铸X张牌。3.可以令至多X名角色各摸一张牌，然后将【太平要术】置入装备区。",
  ["#hj__shoushu_choices"] = "授书：请选择%arg项",
  ["#hj__zhangjiao_aquireSkill"] = "获得“救民”直到本轮结束",
  ["#hj__zhangjiao_recast"] = "令一名角色重铸%arg张牌",
  ["#hj__shoushu_choose2recast"] = "授书：你须重铸%arg张牌",
  ["#hj__equipPeace"] = "令至多%arg名角色各摸一张牌，然后将【太平要术】置入装备区",
  ["#hj__shoushu_choose2draw"] = "授书：令至多%arg名角色各摸一张牌",
  ["#hj__jiumin_prompt"] = "救民：你可以弃置任意张“道”并令等量名角色获得“集兵”",
  ["hj__jiumin"] = "救民",
  [":hj__jiumin"] = "出牌阶段限一次，你可以弃置任意张“道”并令任意名角色获得“集兵”。每轮结束时，你获得所有的“兵”。",
  ["hj__huangjin"] = "黄巾",
  [":hj__huangjin"] = "主公技，其他群势力角色发动“集兵”时，你可以摸一张牌。"
}


return extension
